<?php

namespace App\Http\Controllers;

use App\Jobs\Ceshi;
use App\Jobs\SyncPhoneRecord;
use App\Models\CdrAddtion;
use App\Models\FsUser;
use App\Models\User;
use App\Services\SipService;
use Validator;
use App\Models\Phone;
use App\Models\PhoneRecord;
use App\Services\PlivoService;
use App\Services\TwilioService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Twilio\TwiML\VoiceResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;


class TwilioController extends CallBaseController
{
    protected $twilioSecret;

    public function __construct(TwilioService $twilioService)
    {
        parent::__construct();
        $this->twilioSecret = $twilioService;
    }

    /**
     * @api {get} /api/token 打电话token
     * @apiGroup Phone
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id 客户id
     * @apiParam {int} task_id 任务id
     * @apiParam {int} phone_setting_id 电话配置id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY29wZSI6InNjb3BlOmNsaWVudDpvdXRnb2luZz9hcHBTaWQ9c3Nzc3NkZmZmJmFwcFBhcmFtcz0iLCJpc3MiOiJBQzI1NDhlNDI1ZjBhZTJkYTA0OGRlNjZjZGU0NjQ0ZjZjIiwiZXhwIjoxNTQ1NjE3Mjc5fQ.I1TDipyyeATxe26pjJNMnbf7CRRwndmSaUdNydRGo8E"
     *       }
     */
    public function token(Request $request, TwilioService $twilioService, PlivoService $plivoService){
        $validatedData = $request->validate([
            'id' => 'required|exists:mysql_branch.fs_user,id',
            'task_id'=> 'nullable|exists:tasks,id',
            'phone_setting_id' => 'required|exists:phone_settings,id,status,1'
        ],[],[
            'id'=> '会员'
        ]);
        $phoneSettingId = $validatedData['phone_setting_id'];
        $task_id = $request->input('task_id','');
        //电话配置
        $setting = DB::table('phone_settings')->where('status',1)->first();

        //获取电话号码
        $phones = $this->user()->phones()->where('phone_setting_id',$setting->id)->first();
        if(empty($phones)){
            return response()->json(['error' => '现配置下用户无绑定手机号'], 422);
        }
        //对无效号码的验证
        $to = FsUser::find($validatedData['id'])->phone_num;
        if(!checkMobile($to)){
            return response()->json(['error' => '错误的电话号码'], 422);
        }
        $from = $phones->phone_number;
        if($setting->type == 'twilio'){
            $to = fullPhone(FsUser::find($validatedData['id'])->phone_num);
            $apps = $phones->apps;
            //后台用户id
            $user_id = Auth::id();
            //更新XML电话路径
            $twilioService->updateSid($apps, $to, $from,$validatedData['id'],$user_id,$task_id,$phoneSettingId);
            //查找登陆用户对应的APPSID
            $clientToken = app('clientToken');
            $clientToken->allowClientOutgoing($apps);
            $token = $clientToken->generateToken(600);
            Log::info('返回电话Token',['token'=>$token]);
            return response()->json(['type'=>'twilio','data'=>['token' => $token]]);
        }elseif($setting->type == 'plivo'){
            //Plivo
            $to = fullPhone(FsUser::find($validatedData['id'])->phone_num);
            $user_id = Auth::id();
            //更新应用的XML地址
            $res = $plivoService->editApp($phones->apps,$to,$validatedData['id'],$user_id,$task_id,$from,$phoneSettingId);
            if($res){
                Log::info('返回电话账号密码',['username'=>$phones->username,'password'=>$phones->password]);
                return response()->json(['type'=>'plivo','data'=>['username'=>$phones->username,'password'=>$phones->password]]);
            }else{
                return response()->json(['error' => '修改URL失败'], 422);
            }
        }elseif ($setting->type == 'sip'){
            $to = FsUser::find($validatedData['id'])->phone_num;
            //后台用户id
            $user_id = Auth::id();

            //SIP写入一条通话记录
            $phone_record = new PhoneRecord([
                'fs_user_id' => $validatedData['id'],
                'user_id' => $user_id,
                'task_id' => empty($task_id)?null:$task_id,
                'phone_setting_id' => $validatedData['phone_setting_id'],
                'created_at' => Carbon::now(),
                'user_phone' => $from,
                'fs_user_phone' => '9286'.$to
            ]);
            $phone_record->save();
            //会员微信存在则通话次数+1，否则创建一个为1的空微信
            $res = DB::table('fs_user_has_ims')->where('fs_user_id',$validatedData['id'])->count();
            if($res){
                DB::table('fs_user_has_ims')->where([
                    ['fs_user_id','=',$validatedData['id']],
                ])->increment('phone_num');
            }else{
                $res = DB::table('fs_user_has_ims')->insert([
                    'fs_user_id' =>$validatedData['id'],
                    'phone_num' => 1,
                ]);
            }

            //通话状态为0的时候才去修改
            if(isset($validatedData['task_id'])){
                $res = DB::table('fs_user_tasks')->where([
                    ['task_id','=', $validatedData['task_id']],
                    ['fs_user_id','=', $validatedData['id']],
                ])->first();
                if($res->status===0){
                    DB::table('fs_user_tasks')->where([
                        ['task_id','=', $validatedData['task_id']],
                        ['fs_user_id','=', $validatedData['id']],
                    ])->update(['status'=>1,'call_time'=>Carbon::now()]);
                }
            }
            //延迟任务
            $this->dispatch(new SyncPhoneRecord($phone_record,60 * env('SYNC_SIP_RECORD')));
            return response()->json(['type'=>'sip','data'=>['username'=> $phones->username,'phone'=>$to]]);
        }
    }

    //Twilio的XML
    public function responesXml(Request $request){
        $to = $request->input('to');
        $from = $request->input('from');
        $fs_user_id = $request->input('id');
        $user_id = $request->input('user_id');
        $task_id = $request->input('task_id','');
        $response = new VoiceResponse();
        $dial = $response->dial('', ['callerId' => $from, 'record'=>"record-from-answer-dual", 'recordingStatusCallback'=>env('APP_URL')."/api/voice" ,'recordingStatusCallbackMethod'=>"POST"]);
        $dial->number($to,[
            'statusCallback' => env('APP_URL')."/api/record?id={$fs_user_id}&user_id={$user_id}&task_id={$task_id}",
        ]);

        echo $response;
    }
    //接通电话时
    public function record(Request $request){
        $data = $request->all();
        Log::info('接通电话时',$data);
        PhoneRecord::create([
            'call_sid'=> $data['CallSid'],
            'fs_user_id' => $data['id'],
            'user_id' => $data['user_id'],
            'task_id' => $data['task_id'],
            'apps'=>  $data['ApplicationSid'],
            'recording_time'=> $data['CallDuration'],
            'call_status'=> $data['CallStatus'],
            'recording_sid'=> empty($data['RecordingSid'])?'':$data['RecordingSid'],
            'created_at'=> date('Y-m-d H:i:s',strtotime($data['Timestamp'])),
        ]);
        //通话状态为0的时候才去修改
        if(!empty($data['task_id'])){
            $res = DB::table('fs_user_tasks')->where([
                ['task_id','=',$data['task_id']],
                ['fs_user_id','=',$data['id']],
            ])->first();
            if($res->status===0){
                DB::table('fs_user_tasks')->where([
                    ['task_id','=',$data['task_id']],
                    ['fs_user_id','=',$data['id']],
                ])->update(['status'=>1,'call_time'=>Carbon::now()]);
            }
        }

        //会员微信存在则通话次数+1，否则创建一个为1的空微信
        $res = DB::table('fs_user_has_ims')->where('fs_user_id',$data['id'])->count();
        if($res){
            DB::table('fs_user_has_ims')->where([
                ['fs_user_id','=',$data['id']],
            ])->increment('phone_num');
        }else{
            $res = DB::table('fs_user_has_ims')->insert([
                'fs_user_id' =>$data['id'],
                'phone_num' => 1,
            ]);
        }
        //统计任务
        if(!empty($data['task_id'])){
            $arr = [
                'fs_user_id' => $data['id'],
                'task_id' => $data['task_id']
            ];
            $this->twilioSecret->taskStatus($arr);
        }
    }

    //结束电话时
    public function voice(Request $request){
        $data = $request->all();
        //录音下载到本地
        if($data['RecordingSid']){
            $voice_url = voiceUpload($data['RecordingUrl'],$data['RecordingSid']);
        }
        PhoneRecord::where('recording_sid',$data['RecordingSid'])->update([
            'updated_at'=>date('Y-m-d H:i:s',strtotime($data['RecordingStartTime'])),
            'recording_url'=> $data['RecordingUrl'],
            'voice_url' => $voice_url
        ]);
        Log::info('结束电话时',$data);
    }

    //购买电话
    public function buyNumber(){
        $res = $this->twilioSecret->buy();
        $res = Phone::create($res);
        Log::info('create_phone',['购买手机号成功,ID是'.$res->id]);
    }

    public function test(){
//        Ceshi::dispatch();
    }
}
